<?php
/**
 * @copyright 码小象 www.uxphp.com
 * www.yxxhui.com
 * www.mxxiang.com
 * www.mxxiang.cn
 * 自研正版源码，赋能开发者
 */

namespace app\services\care;


use app\dao\care\ServicePlaceDao;
use app\model\care\ServicePlace;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;

class ServicePlaceServices extends BaseServices
{
    public function __construct(ServicePlaceDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 服务开通列表
     * @param array $where
     * @param bool $is_page
     * @return array
     */
    public function getList(array $where = [],bool $is_page = false)
    {
        /** @var ServiceItemServices $itemServices */
        $itemServices = app()->make(ServiceItemServices::class);
        $field = 'i.id,i.title,i.thumb';
        $result = $itemServices->getList($where,$field,$is_page);
        $list = $result['list'];
        $count = $result['count'];
        $itemIds = $this->dao->getColumn(['place_id'=>$where['place_id']],'item_id');
        foreach ($list as &$item) {
            $item['is_open'] = in_array($item['id'], $itemIds);
        }
        unset($item);
        return compact('list','count');
    }

    /**
     * 获取地点关联的服务
     * @param $place_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPlaceItem($place_id){
        $place_item = ServicePlace::where('place_id','=',$place_id)->select()->toArray();
        return $place_item;
    }

    /**
     * 开启|关闭服务
     * @param $data
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function open($data){
        $info = $this->dao->getOne(['place_id'=>$data['place_id'],'item_id'=>$data['item_id']]);
        if($info){
            if(!$this->dao->delete($info['id'])){
                throw new AdminException('关闭失败');
            }
        }else{
            $data['add_time'] = time();
            if(!$this->dao->save($data)){
                throw new AdminException('开启失败');
            }
        }
        return $info ? '关闭成功' : '开启成功';
    }
}
